package com.itxiaowu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itxiaowu.constant.MessageConstant;
import com.itxiaowu.entity.Result;
import com.itxiaowu.pojo.Setmeal;
import com.itxiaowu.service.MemberService;
import com.itxiaowu.service.OrderService;
import com.itxiaowu.service.ReportService;
import com.itxiaowu.service.SetmealService;
import com.itxiaowu.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 报表类
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;   // 会员

    @Reference
    private SetmealService setmealService;

    @Reference
    private OrderService orderService;

    @Reference
    public ReportService reportService;

    /**
     *  1： 获得会员注册数据
     */
    @RequestMapping("/getMemberReport.do")
    public Result getMemberReport(){


        try {
            // 1:获得当前月份
            Calendar instance = Calendar.getInstance();
            //   1.1: 进行转换
            String newDate = DateUtils.parseDate2String(instance.getTime());

            // 2:获得12个月前的时间
            instance.add(Calendar.MONTH,-12);

            // 3:进行遍历至当前月今日
            List<String> months = new ArrayList();
            for(int i = 0; i < 12; i++){
                // 3.1: 进行日期转换
                instance.add(Calendar.MONTH,1);
                String beforeDate = DateUtils.parseDate2String(instance.getTime(), "yyyy-MM");
                months.add(beforeDate);
            }

            //  3.2 查询数据库获得数据
            List<Integer> memberCount = memberService.getMemberReport(months);

            // 4:将查询数据进行返回
            Map<String, Object> map = new HashMap<>();
            map.put("months",months);
            map.put("memberCount",memberCount);

            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /**
     *  2: 查询套餐占比   setmealNames  setmealCount
     *  "setmealCount":[
*                            {"name":"套餐1","value":10},
*                            {"name":"套餐2","value":30},
*                            {"name":"套餐3","value":25}
     * 						   ]
     */
    @RequestMapping("/getSetmealReport.do")
    public Result getSetmealReport(){

        try{

            Map<String,Object> map = new HashMap<>();

            // 1： 获得全部套餐的名字
            List<Setmeal> setmealList = setmealService.getSetmeal();

            // 2: 根据套餐id查询预约人数
            List<String> setmealNames = new ArrayList<>();
            List<Map<String,Object>> setmealCount = new ArrayList<>();


            for (Setmeal setmeal : setmealList) {
                Map<String,Object> hash = new HashMap<>();
                //3： 进行添加数据
                // 3.1: 添加套餐名称
                setmealNames.add(setmeal.getName());
                // 3.2:添加预约人数
                Integer count = orderService.findCountBySetmealId(setmeal.getId());

                hash.put("name",setmeal.getName());
                hash.put("value",count);
                setmealCount.add(hash);
            }

            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealCount);

            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     *  3: 查询运营数据
     *
     */
    @RequestMapping("/getBusinessReportData.do")
    public Result getBusinessReportData(){
        try {

        /*
            1：查询数据
         */
            Map<String, Object> map = reportService.getBusinessReportData();

        /*
            2: 返回数据
         */
           return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        }catch(Exception e){
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     *  下载模板文件
     */
    @RequestMapping("/exportBusinessReport.do")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){


        try {
            /*
             1: 获得表格中的所有数据
             */
            Map<String, Object> map = reportService.getBusinessReportData();
            // 1.1: 将数据全部拆分出来
            String reportDate = String.valueOf(map.get("reportDate"));
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");

            /*
                2: 进行表格赋值
             */
            // 2.1：在内存中写入一个表格
            String template = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";
            // 2.2: 读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(template)));
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            /*
                3: 写出数据   -- > 先获取行数据， 以行数据找列 行以0开始， 列以1开始
             */
            XSSFRow row1 = sheetAt.getRow(2);
            row1.getCell(5).setCellValue(reportDate);

            XSSFRow row2 = sheetAt.getRow(4);
            row2.getCell(5).setCellValue(todayNewMember);
            row2.getCell(7).setCellValue(totalMember);

            XSSFRow row3 = sheetAt.getRow(5);
            row3.getCell(5).setCellValue(thisWeekNewMember);
            row3.getCell(7).setCellValue(thisMonthNewMember);

            XSSFRow row4 = sheetAt.getRow(7);
            row4.getCell(5).setCellValue(todayOrderNumber);
            row4.getCell(7).setCellValue(todayVisitsNumber);

            XSSFRow row5 = sheetAt.getRow(8);
            row5.getCell(5).setCellValue(thisWeekOrderNumber);
            row5.getCell(7).setCellValue(thisWeekVisitsNumber);

            XSSFRow row6 = sheetAt.getRow(9);
            row6.getCell(5).setCellValue(thisMonthOrderNumber);
            row6.getCell(7).setCellValue(thisMonthVisitsNumber);

            //最后一行是数组形式
            // 此处是13 行  ， 则是row = 12
            int rowNum = 12;
            for(Map hash : hotSetmeal){

                String name = (String) hash.get("name");
                Long setmeal_count = (Long) hash.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) hash.get("proportion");

                // 写入表格
                XSSFRow row = sheetAt.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            // 关闭资源
            out.flush();
            out.close();
            workbook.close();
            return null;


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    @RequestMapping("/getMemberSexReport.do")
    public Result getMemberSexReport() {
        try {
            List<Map<String, Object>> list = memberService.getMemberSexReport();

            Map<String, Object> map= new HashMap<>();

            List<Map<String, Object>> list2 =new ArrayList<>();
            List<String> sex = new ArrayList<>();
            for (Map<String, Object> m : list) {
                String name = (String) m.get("name");
                if (name == null){
                    name="未知性别";
                }if(name.equals("1")){
                    name="男";
                }if(name.equals("2")){
                    name="女";
                }
                Map<String,Object>map1=new HashMap<>();
                map1.put("name",name);
                Object value = m.get("value");
                map1.put("value",value);
                list2.add(map1);
                sex.add(name);
            }
            map.put("memberCount",list2);
            map.put("sex", sex);
            return new Result(true, "查询性别数据成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询性别数据成功");
        }
    }
    @RequestMapping("/getMemberBirthdayReport")
    public Result getMemberBirthdayReport() {
        Map<String, Object> map = null;
        try {
            map = memberService.getMemberBirthdayReport();
            return new Result(true, "查询会员年龄成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询会员年龄失败");
        }
    }

/**  根据月份查询会员人数*/

@RequestMapping("/getMemberReportByMonth.do")
 public Result getMemberReport(@RequestBody Map map1 ) {
     try {
         String startTime = (String) map1.get("startTime");
         String endTime = (String) map1.get("endTime");
         List<String> list = DateUtils.getMonthBetween(startTime, endTime, "yyyy-MM");
         List<Integer> memberCount = memberService.getMemberReportByMonth(list);
         Map<String, Object> map = new HashMap<>();
         map.put("list", list);
         map.put("memberCount", memberCount);

         return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);

     } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
     }
    }



 // 使用日期查询工具进行查看日趋数据， 方便进行数据转换
//    public static void main(String[] args) {
//        Calendar instance = Calendar.getInstance();
//        Date time = instance.getTime();
//        System.out.println(time);
//        instance.add(Calendar.MONTH,-12);
//        time = instance.getTime();
//        System.out.println(time);
//    }

}
